/*
    This file is part of Emu.

    Emu is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Emu is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Emu.  If not, see <http://www.gnu.org/licenses/>. */
#include <QKeySequence>

QString textFromPress(int press)
{
    /* The keypad modifier breaks the converter for some reason. Besides, doing it this
        way means that whatever macro is defined works with or without being used on the
        keypad. Think of it as a feature. :) */
    press &= ~Qt::KeypadModifier;

    QKeySequence k = QKeySequence(press);

    /* Qt uses commas to separate multiple key presses. Can't emulate that with the
        current macros, so don't let it pass. */
    if (k.count() != 1)
        return "";

    /* Make sure this isn't an invalid or modifier-only press. */
    int checkPress = press & ~(Qt::ShiftModifier | Qt::MetaModifier |
                               Qt::ControlModifier | Qt::AltModifier);

    if (checkPress == 0 || checkPress == Qt::Key_unknown ||
        checkPress == Qt::Key_Shift || checkPress == Qt::Key_Meta ||
        checkPress == Qt::Key_Alt || checkPress == Qt::Key_Control)
        /* Invalid, or modifiers only. */
        return "";
    else
        return QKeySequence(press).toString();
}

int pressFromText(QString text)
/* Convert some text to a macro press. If the macro is bad, return 0 to indicate
    failure. */
{
    QKeySequence k = QKeySequence::fromString(text)[0];

    /* Either the text is blank, or contains a complex Emacs-style keypress. */
    if (k.count() != 1)
        return 0;

    int initPress = k[0];

    /* Modifiers aren't required because somebody might just want to capture F1 or Page
        Up by itself. However, do make sure that there's a key. */
    int checkPress = initPress & ~(Qt::ShiftModifier | Qt::MetaModifier |
                                   Qt::ControlModifier | Qt::AltModifier);

    if (checkPress == 0 || checkPress == Qt::Key_unknown)
        /* Either no key, or an unknown one. */
        return 0;
    else
        /* It's good. Return it. */
        return initPress;
}

